package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.UserOrderService;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websockets.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserOrderServiceImpl implements UserOrderService {
    @Autowired
    private UserOrderMapper userOrderMapper;
    @Autowired
    private UserOrderDetailMapper userOrderDetailMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserShoppingCartMapper userShoppingCartMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    @Transactional
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        // 处理各种业务异常（购物车商品为空、地址铺为空、）
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCartList = userShoppingCartMapper.list(shoppingCart);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 向“订单表”插入一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setUserName(addressBook.getConsignee());
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orders.setPackAmount(shoppingCartList.size() * 2);

        userOrderMapper.insert(orders);

        // 向“订单明细表”插入N条数据
        ArrayList<OrderDetail> orderDetailArrayList = new ArrayList<>();
        shoppingCartList.forEach(item -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailArrayList.add(orderDetail);
        });
        userOrderDetailMapper.insertBatch(orderDetailArrayList);

        // 清空购物车商品数据
        userShoppingCartMapper.delete(shoppingCart);

        // 返回"OrderSubmitVO"数据
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO();
        orderSubmitVO.setId(orders.getId());
        orderSubmitVO.setOrderAmount(orders.getAmount());
        orderSubmitVO.setOrderNumber(orders.getNumber());
        orderSubmitVO.setOrderTime(orders.getOrderTime());

        return orderSubmitVO;
    }

    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) {
        if (ordersPaymentDTO.getOrderNumber() == null || ordersPaymentDTO.getOrderNumber().isEmpty()) {
            throw new OrderBusinessException("订单编号不能为空！！！！");
        }

        Orders orders = new Orders();
        orders.setNumber(ordersPaymentDTO.getOrderNumber());
        orders.setPayMethod(ordersPaymentDTO.getPayMethod());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setPayStatus(Orders.PAID);
        orders.setCheckoutTime(LocalDateTime.now());

        userOrderMapper.update(orders);

        OrderPaymentVO orderPaymentVO = new OrderPaymentVO();
        orderPaymentVO.setTimeStamp(String.valueOf(System.currentTimeMillis()));


        // 通知商家来单了
        Orders byOrderNumber = userOrderMapper.getByOrderNumber(ordersPaymentDTO.getOrderNumber());
        Map map = new HashMap<>();
        map.put("type", 1); /* 1-来单提醒 2-客户催单 */
        map.put("orderId", byOrderNumber.getId());
        map.put("content", "订单号：" + ordersPaymentDTO.getOrderNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

        return orderPaymentVO;
    }

    @Override
    public OrderVO orderDetail(Long id) {
        Orders orders = userOrderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(id);
        List<OrderDetail> orderDetailList = userOrderDetailMapper.list(orderDetail);

        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Orders orders = new Orders();
        orders.setUserId(BaseContext.getCurrentId());
        if (ordersPageQueryDTO.getStatus() != null) {
            orders.setStatus(ordersPageQueryDTO.getStatus());
        }
        Page<Orders> page = userOrderMapper.list(orders);

        List<OrderVO> orderVOArrayList = page.getResult().stream().map(item -> {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(item, orderVO);

            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(item.getId());
            ArrayList<OrderDetail> orderDetailArrayList = userOrderDetailMapper.list(orderDetail);
            orderVO.setOrderDetailList(orderDetailArrayList);

            return orderVO;
        }).collect(Collectors.toList());

        return PageResult.success(page.getTotal(), orderVOArrayList);
    }

    @Transactional
    @Override
    public Result<Object> repetition(Long id) {
        Orders orders = userOrderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException("无效订单！！！");
        }

        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setOrderId(id);
        ArrayList<OrderDetail> orderDetailList = userOrderDetailMapper.list(orderDetail);

        userOrderMapper.insert(orders);
        userOrderDetailMapper.insertBatch(orderDetailList);
        return null;
    }

    @Override
    public void cancel(Long id) {
        Orders orders = userOrderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException("无效订单！！！");
        }

        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(MessageConstant.ORDER_USER_CANCEL);

        userOrderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = userOrderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException("无效订单！！！");
        }

        // 向管理前段发送催单消息
        Map map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + orders.getNumber());
        String jsonString = JSON.toJSONString(map);

        webSocketServer.sendToAllClient(jsonString);
    }
}